<template>
    <div ref="ScrollList" class="sc-message-list">
        <Message
            v-for="(message, idx) in messages"
            :key="idx"
            :message="message"
            @download="(file) => emits('download', file)"
            @message-click="(btnType) => emits('messageClick', btnType)"
            @tabs-click="(id) => emits('tabsClick', id)"
            @reConnect="emits('reConnect')"
            @replyClick="(val) => emits('replyClick', val)"
            @refresh="(val) => emits('refresh', val)"
        >
            <template v-slot:time>
                <span v-if="idx === 0">Chat started at {{ message.meta }}</span>

                <span v-if="showDate(idx)">{{ message.meta }}</span>
            </template>
        </Message>
    </div>
</template>

<script setup>
import { computed, watch, nextTick, ref } from 'vue'
import Message from './Message.vue'

const props = defineProps({
    messages: {
        type: Array,
        required: true,
    },
})

const emits = defineEmits([
    'download',
    'messageClick',
    'tabsClick',
    'reConnect',
    'replyClick',
    'refresh',
])

const showDate = computed(() => {
    return (index) => {
        return index > 0 && props.messages[index].meta !== props.messages[index - 1].meta
    }
})

const ScrollList = ref()

watch(
    () => props.messages,
    (val) => {
        scrollDown()
    }
)

const scrollDown = () => {
    nextTick(() => {
        const element = ScrollList.value
        if (element) {
            // 执行滚动操作
            element.scrollTo({
                top: element.scrollHeight,
                behavior: 'auto',
            })

            // 增加检查点，确保滚动到位
            const checkScrollPosition = () => {
                if (element.scrollTop + element.clientHeight < element.scrollHeight) {
                    // 如果未滚动到底部，立即滚动到最底部
                    element.scrollTo({
                        top: element.scrollHeight,
                        behavior: 'auto',
                    })
                }
            }

            // 使用 setTimeout 确保 DOM 更新和渲染完成
            setTimeout(checkScrollPosition, 500) // 根据实际情况调整延迟时间
        }
    })
}
</script>

<style scoped lang="scss">
.sc-message-list {
    flex: 1;
    overflow-y: auto;
    background-size: 100%;
    padding: 28px 20px;
    background: rgb(248, 248, 248);
}

/* 修改垂直滚动条 */
.sc-message-list::-webkit-scrollbar {
    width: 8px; /* 修改宽度 */
    border-radius: 6px;
}

/* 修改滚动条轨道背景色 */
.sc-message-list::-webkit-scrollbar-track {
    background-color: #f1f1f1;
}

/* 修改滚动条滑块颜色 */
.sc-message-list::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 12px;
}

/* 修改滚动条滑块悬停时的颜色 */
.sc-message-list::-webkit-scrollbar-thumb:hover {
    background-color: #c7c7c7;
}
</style>
